package cn.attackme.myuploader.service;

import cn.attackme.myuploader.config.UploadConfig;

import cn.attackme.myuploader.dao.IconMapper;

import cn.attackme.myuploader.model.Icon;
import cn.attackme.myuploader.utils.FileUtils;

import org.apache.ibatis.annotations.SelectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;

import static cn.attackme.myuploader.utils.UploadUtils.*;

/**
 * 文件上传服务
 */
@Service
public class IconServiceImpl {
    @Autowired
    private IconMapper iconMapper;


    /**
     * 上传图标文件
     * @param md5
     */
    public void upload(String name,
                       String md5,
                       String iconBase64) throws IOException {

        iconMapper.save(new Icon(name, md5, iconBase64, new Date()));
    }

    /**
     * 分块上传文件
     * @param md5
     * @param size
     * @param chunks
     * @param chunk
     * @param file
     * @throws IOException
     */
    public void uploadWithBlock(String name,
                                String md5,
                                Long size,
                                Integer chunks,
                                Integer chunk,
                                MultipartFile file) throws IOException {
        String fileName = getFileName(md5, chunks);
        FileUtils.writeWithBlok(UploadConfig.path + fileName, size, file.getInputStream(), file.getSize(), chunks, chunk);
        addChunk(md5,chunk);
        if (isUploaded(md5)) {
            removeKey(md5);
            iconMapper.save(new Icon(name, md5,UploadConfig.path + fileName, new Date()));
        }
    }

    /**
     * 检查Md5判断文件是否已上传
     * @param md5
     * @return
     */
    public boolean checkMd5(String md5) {
        Icon file = new Icon();
        file.setMd5(md5);
        return iconMapper.getByIcon(file) == null;
    }

    /**
     * 根据图标名称返回图标路径
     * @param name
     * @return
     */
    public Icon getIconByName(String name) {
        Icon icon = iconMapper.getIconByName(name);
        return icon;
    }

    /**
     * 根据Id获取图标信息
     * @param id
     * @return
     */
    public Icon getById(String id){
        return iconMapper.getById(id);
    }

    /**
     * 根据Id删除图标信息
     * @param id
     * @return
     */
    public void deleteById(String id){
        iconMapper.deleteById(id);
    }

    /**
     * 更新一行数据
     * @param icon
     * @return
     */
    public void updateIcon(Icon icon){
        iconMapper.updateIcon(icon);
    }

    public Icon getByIcon(Icon icon){
        Icon icon2 = iconMapper.getByIcon(icon);
        return  icon2;
    }


}
